import { defineStore } from 'pinia';
import type { UserInfo } from '@/api/auth';

type UserType = 'student' | 'teacher' | 'admin';
type Role = 'student' | 'teacher' | 'admin';
type Permission = string;

interface UserState {
    userInfo: UserInfo | null;
    token: string | null;
    roles: Role[];
    permissions: Permission[];
    _initialized: boolean;
    _pending: boolean;
}

// 添加完整的 Store 接口定义
interface UserStoreGetters {
    isLoggedIn: boolean;
    userType: UserType | null;
    fullName: string;
    avatar: string;
    teacherId: string | number | undefined;
    isInitialized: boolean;
    hasRole: (role: Role) => boolean;
    hasPermission: (permission: Permission) => boolean;
}

interface UserStoreActions {
    setUserInfo(userInfo: UserInfo): void;
    setToken(token: string): void;
    setRolesBasedOnType(type: UserType): void;
    clearUserInfo(): void;
    initialize(): Promise<void>;
}

export type UserStore = ReturnType<typeof useUserStore> & UserStoreGetters & UserStoreActions;

export const useUserStore = defineStore('user', {
    state: (): UserState => ({
        userInfo: null,
        token: null,
        roles: [],
        permissions: [],
        _initialized: false,
        _pending: false
    }),

    actions: {
        setUserInfo(userInfo: UserInfo) {
            if (!userInfo.type && userInfo.role) {
                userInfo.type = userInfo.role.toLowerCase() as UserType;
            }
            this.userInfo = userInfo;
            this.setRolesBasedOnType(userInfo.type);
        },

        setToken(token: string) {
            if (!token) {
                throw new Error('Token cannot be empty');
            }
            this.token = token;
            localStorage.setItem('token', token);
        },

        setRolesBasedOnType(type: UserType) {
            switch (type) {
                case 'student':
                    this.roles = ['student'];
                    this.permissions = ['view_courses', 'join_classes', 'submit_assignments'];
                    break;
                case 'teacher':
                    this.roles = ['teacher'];
                    this.permissions = ['create_courses', 'manage_classes', 'grade_assignments'];
                    break;
                case 'admin':
                    this.roles = ['admin'];
                    this.permissions = ['manage_users', 'system_config', 'view_reports'];
                    break;
                default:
                    throw new Error(`Unknown user type: ${type}`);
            }
        },

        clearUserInfo() {
            this.userInfo = null;
            this.token = null;
            this.roles = [];
            this.permissions = [];
            this._initialized = false;
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
        },

        async initialize() {
            if (this._initialized) return;

            const token = localStorage.getItem('token');
            const userInfoStr = localStorage.getItem('userInfo');

            if (token && userInfoStr) {
                this.token = token;

                try {
                    const userInfo = JSON.parse(userInfoStr);
                    const mappedUserInfo = {
                        ...userInfo,
                        type: userInfo.role?.toLowerCase() as UserType || 'student'
                    };

                    this.setUserInfo(mappedUserInfo);
                    console.log('✅ 从本地存储初始化用户信息成功');
                } catch (error) {
                    console.error('❌ 解析本地用户信息失败', error);
                    this.clearUserInfo();
                }
            }
            this._initialized = true;
        },
    },

    getters: {
        isLoggedIn: (state) => !!state.token,
        userType: (state): UserType | null => state.userInfo?.type || null,
        fullName: (state) => state.userInfo?.name || '',
        avatar: (state) => state.userInfo?.avatar || '',
        hasRole: (state) => (role: Role) => state.roles.includes(role),
        hasPermission: (state) => (permission: Permission) =>
            state.permissions.includes(permission),
        teacherId: (state) => state.userInfo?.teacherId || state.userInfo?.id,
        isInitialized: (state) => state._initialized,
    },

    persist: {
        key: 'user-store',
        paths: ['token'],
    },
});
